<template>
  <div class="game-container" 
       @keydown="handleKeyDown" 
       @keyup="handleKeyUp" 
       tabindex="0">
    <div class="game-info">
      <div class="score">分数: {{ score }}</div>
      <div class="lives">生命值: {{ lives }}</div>
      <div class="high-score">最高分: {{ highScore }}</div>
      <div class="level">关卡: {{ level }}</div>
      <div class="power-ups">
        <div v-if="powerUpInfo.shield" class="power-up shield">{{ powerUpInfo.shield }}</div>
        <div v-if="powerUpInfo.doubleShot" class="power-up double-shot">{{ powerUpInfo.doubleShot }}</div>
        <div v-if="powerUpInfo.laser" class="power-up laser">{{ powerUpInfo.laser }}</div>
      </div>
    </div>
    
    <div class="game-area" ref="gameArea">
      <div class="player" :style="playerStyle">
        <div v-if="hasShield" class="shield-effect"></div>
      </div>
      <div v-for="bullet in bullets" 
           :key="bullet.id" 
           class="bullet"
           :class="bulletClass(bullet)"
           :style="bulletStyle(bullet)"></div>
      <div v-for="enemy in enemies" 
           :key="enemy.id" 
           class="enemy"
           :class="enemyClass(enemy)"
           :style="enemyStyle(enemy)"></div>
      <div v-for="powerUp in powerUps" 
           :key="powerUp.id" 
           class="power-up-item"
           :class="powerUpClass(powerUp)"
           :style="powerUpStyle(powerUp)"></div>
      <div v-for="explosion in explosions" 
           :key="explosion.id" 
           class="explosion"
           :style="explosionStyle(explosion)"></div>
      <div v-for="bullet in enemyBullets" 
           :key="bullet.id" 
           class="enemy-bullet"
           :style="{
             left: `${bullet.x}px`,
             top: `${bullet.y}px`
           }"></div>
    </div>

    <div v-if="!gameStarted" class="start-screen">
      <h2>太空战机</h2>
      <p>按空格键开始游戏</p>
      <div class="controls">
        <p>← →: 左右移动</p>
        <p>↑ ↓: 上下移动</p>
        <p>空格键: 射击</p>
        <p>P: 暂停</p>
      </div>
    </div>

    <div v-if="gameOver" class="game-over">
      <h2>游戏结束!</h2>
      <p>最终分数: {{ score }}</p>
      <p>达到关卡: {{ level }}</p>
      <button @click="restartGame">重新开始</button>
    </div>

    <div v-if="isPaused" class="pause-screen">
      <h2>游戏暂停</h2>
      <p>按 P 继续游戏</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'

// 游戏常量
const GAME_WIDTH = 800
const GAME_HEIGHT = 600
const PLAYER_WIDTH = 50
const PLAYER_HEIGHT = 50
const PLAYER_SPEED = 5
const BULLET_WIDTH = 4
const BULLET_HEIGHT = 10
const BULLET_SPEED = 10
const ENEMY_WIDTH = 40
const ENEMY_HEIGHT = 40
const ENEMY_SPAWN_RATE = 1000
const SHOOT_COOLDOWN = 300
const POWER_UP_SPAWN_RATE = 10000
const ENEMY_BULLET_SPEED = 5
const ENEMY_SHOOT_COOLDOWN = 2000 // 敌人射击冷却时间

// 图片路径
const IMAGES = {
  player: '/images/player.png',
  enemySmall: '/images/enemy-small.png',
  enemyMedium: '/images/enemy-medium.png',
  enemyLarge: '/images/enemy-large.png',
  enemyElite: '/images/enemy-elite.png',
  enemyBoss: '/images/enemy-boss.png',
  bullet: '/images/bullet.png',
  laserBullet: '/images/laser-bullet.png',
  shield: '/images/shield.png',
  doubleShot: '/images/double-shot.png',
  laser: '/images/laser.png',
  explosion: '/images/explosion.png'
}

// 游戏状态
const score = ref(0)
const lives = ref(3)
const gameOver = ref(false)
const gameStarted = ref(false)
const highScore = ref(localStorage.getItem('highScore') || 0)
const gameArea = ref(null)
const level = ref(1)
const isPaused = ref(false)

// 玩家状态
const playerX = ref(GAME_WIDTH / 2 - PLAYER_WIDTH / 2)
const playerY = ref(GAME_HEIGHT - PLAYER_HEIGHT - 20)
const isMovingLeft = ref(false)
const isMovingRight = ref(false)
const isMovingUp = ref(false)
const isMovingDown = ref(false)
const canShoot = ref(true)

// 道具状态
const hasShield = ref(false)
const hasDoubleShot = ref(false)
const hasLaser = ref(false)
const powerUps = ref([])
let lastPowerUpSpawn = 0

// 道具等级
const powerUpLevels = ref({
  shield: 0,
  doubleShot: 0,
  laser: 0
})

// 游戏对象
const bullets = ref([])
const enemyBullets = ref([]) // 添加敌人子弹数组
const enemies = ref([])
const explosions = ref([])
let lastEnemySpawn = 0
let gameLoop = null
let enemySpawnInterval = null
let powerUpSpawnInterval = null

// 音效
const sounds = {
  shoot: new Audio('/sounds/shoot.mp3'),
  explosion: new Audio('/sounds/explosion.mp3'),
  powerUp: new Audio('/sounds/powerup.mp3'),
  hit: new Audio('/sounds/hit.mp3'),
  background: new Audio('/sounds/background.mp3')
}

// 计算样式
const playerStyle = computed(() => ({
  left: `${playerX.value}px`,
  top: `${playerY.value}px`,
  backgroundImage: `url(${IMAGES.player})`
}))

const bulletStyle = (bullet) => ({
  left: `${bullet.x}px`,
  top: `${bullet.y}px`,
  backgroundImage: `url(${bullet.type === 'laser' ? IMAGES.laserBullet : IMAGES.bullet})`
})

const enemyStyle = (enemy) => ({
  left: `${enemy.x}px`,
  top: `${enemy.y}px`,
  width: `${ENEMY_WIDTH * enemy.size}px`,
  height: `${ENEMY_HEIGHT * enemy.size}px`,
  backgroundImage: `url(${IMAGES[`enemy${enemy.type.charAt(0).toUpperCase() + enemy.type.slice(1)}`]})`
})

const powerUpStyle = (powerUp) => ({
  left: `${powerUp.x}px`,
  top: `${powerUp.y}px`,
  backgroundImage: `url(${IMAGES[powerUp.type]})`
})

const explosionStyle = (explosion) => ({
  left: `${explosion.x}px`,
  top: `${explosion.y}px`,
  backgroundImage: `url(${IMAGES.explosion})`
})

const bulletClass = (bullet) => ({
  'laser-bullet': bullet.type === 'laser'
})

const enemyClass = (enemy) => ({
  'enemy-small': enemy.type === 'small',
  'enemy-medium': enemy.type === 'medium',
  'enemy-large': enemy.type === 'large',
  'enemy-elite': enemy.type === 'elite',
  'enemy-boss': enemy.type === 'boss'
})

const powerUpClass = (powerUp) => ({
  'shield-power': powerUp.type === 'shield',
  'double-shot-power': powerUp.type === 'doubleShot',
  'laser-power': powerUp.type === 'laser'
})

// 键盘控制
const handleKeyDown = (e) => {
  if (!gameStarted.value) {
    if (e.code === 'Space') {
      startGame()
    }
    return
  }

  if (gameOver.value) return

  switch(e.code) {
    case 'ArrowLeft':
      isMovingLeft.value = true
      break
    case 'ArrowRight':
      isMovingRight.value = true
      break
    case 'ArrowUp':
      isMovingUp.value = true
      break
    case 'ArrowDown':
      isMovingDown.value = true
      break
    case 'Space':
      if (canShoot.value) {
        shoot()
      }
      break
    case 'KeyP':
      togglePause()
      break
  }
}

const handleKeyUp = (e) => {
  switch(e.code) {
    case 'ArrowLeft':
      isMovingLeft.value = false
      break
    case 'ArrowRight':
      isMovingRight.value = false
      break
    case 'ArrowUp':
      isMovingUp.value = false
      break
    case 'ArrowDown':
      isMovingDown.value = false
      break
  }
}

// 游戏动作
const shoot = () => {
  const bulletType = hasLaser.value ? 'laser' : 'normal'
  const bulletWidth = bulletType === 'laser' ? 8 : BULLET_WIDTH
  const bulletHeight = bulletType === 'laser' ? 20 : BULLET_HEIGHT

  if (hasDoubleShot.value) {
    // 根据双发等级决定发射的子弹数量
    const bulletCount = Math.min(2 + powerUpLevels.value.doubleShot, 5) // 最多5发子弹
    const newBullets = []
    
    for (let i = 0; i < bulletCount; i++) {
      const offset = (i - (bulletCount - 1) / 2) * (PLAYER_WIDTH / (bulletCount + 1))
      newBullets.push({
        id: Date.now() + i,
        x: playerX.value + PLAYER_WIDTH / 2 + offset - bulletWidth / 2,
        y: playerY.value,
        width: bulletWidth,
        height: bulletHeight,
        type: bulletType,
        damage: bulletType === 'laser' ? 1 : 1 // 激光子弹的伤害值
      })
    }
    bullets.value = [...bullets.value, ...newBullets]
  } else {
    // 单发子弹
    bullets.value.push({
      id: Date.now(),
      x: playerX.value + PLAYER_WIDTH / 2 - bulletWidth / 2,
      y: playerY.value,
      width: bulletWidth,
      height: bulletHeight,
      type: bulletType,
      damage: bulletType === 'laser' ? 1 : 1 // 激光子弹的伤害值
    })
  }

  sounds.shoot.play()
  canShoot.value = false
  setTimeout(() => {
    canShoot.value = true
  }, SHOOT_COOLDOWN)
}

// 敌人射击函数
const enemyShoot = (enemy) => {
  const bulletCount = enemy.type === 'boss' ? 6 : enemy.type === 'elite' ? 3 : 0
  if (bulletCount === 0) return

  const newBullets = []
  for (let i = 0; i < bulletCount; i++) {
    const angle = (i - (bulletCount - 1) / 2) * (Math.PI / 6) // 子弹角度分布
    newBullets.push({
      id: Date.now() + i,
      x: enemy.x + enemy.width / 2 - BULLET_WIDTH / 2,
      y: enemy.y + enemy.height,
      width: BULLET_WIDTH,
      height: BULLET_HEIGHT,
      speedX: Math.sin(angle) * ENEMY_BULLET_SPEED,
      speedY: Math.cos(angle) * ENEMY_BULLET_SPEED
    })
  }
  enemyBullets.value = [...enemyBullets.value, ...newBullets]
}

// 修改生成敌人函数
const spawnEnemy = () => {
  const types = [
    { type: 'small', speed: 3, health: 1, color: '#f00', score: 100, size: 1 },
    { type: 'medium', speed: 2, health: 2, color: '#f60', score: 200, size: 1 },
    { type: 'large', speed: 1, health: 3, color: '#f90', score: 300, size: 1 },
    { type: 'elite', speed: 1.5, health: 5, color: '#f0f', score: 500, size: 2, lastShot: 0 },
    { type: 'boss', speed: 0.8, health: 10, color: '#0ff', score: 1000, size: 4, lastShot: 0 }
  ]
  
  // 根据关卡调整敌人类型出现的概率
  let availableTypes = types
  if (level.value < 3) {
    availableTypes = types.slice(0, 3) // 只出现普通敌人
  } else if (level.value < 5) {
    availableTypes = types.slice(0, 4) // 出现普通和精英敌人
  }
  
  const type = availableTypes[Math.floor(Math.random() * availableTypes.length)]
  
  const enemy = {
    id: Date.now(),
    x: Math.random() * (GAME_WIDTH - ENEMY_WIDTH * type.size),
    y: -ENEMY_HEIGHT * type.size,
    width: ENEMY_WIDTH * type.size,
    height: ENEMY_HEIGHT * type.size,
    speed: type.speed,
    health: type.health,
    color: type.color,
    score: type.score,
    type: type.type,
    size: type.size,
    lastShot: 0
  }

  enemies.value.push(enemy)
}

// 生成道具
const spawnPowerUp = () => {
  const types = ['shield', 'doubleShot', 'laser']
  const type = types[Math.floor(Math.random() * types.length)]
  
  const powerUp = {
    id: Date.now(),
    x: Math.random() * (GAME_WIDTH - 30),
    y: -30,
    width: 30,
    height: 30,
    type,
    speed: 2
  }

  powerUps.value.push(powerUp)
}

// 创建爆炸效果
const createExplosion = (x, y) => {
  const explosion = {
    id: Date.now(),
    x,
    y,
    size: 40,
    frame: 0
  }
  explosions.value.push(explosion)
  sounds.explosion.play()
  
  // 爆炸动画
  const animateExplosion = () => {
    explosion.frame++
    if (explosion.frame < 8) {
      requestAnimationFrame(animateExplosion)
    } else {
      explosions.value = explosions.value.filter(e => e.id !== explosion.id)
    }
  }
  animateExplosion()
}

// 游戏循环
const updateGame = () => {
  if (!gameStarted.value || gameOver.value || isPaused.value) return

  // 更新玩家位置
  if (isMovingLeft.value) {
    playerX.value = Math.max(0, playerX.value - PLAYER_SPEED)
  }
  if (isMovingRight.value) {
    playerX.value = Math.min(GAME_WIDTH - PLAYER_WIDTH, playerX.value + PLAYER_SPEED)
  }
  if (isMovingUp.value) {
    playerY.value = Math.max(0, playerY.value - PLAYER_SPEED)
  }
  if (isMovingDown.value) {
    playerY.value = Math.min(GAME_HEIGHT - PLAYER_HEIGHT, playerY.value + PLAYER_SPEED)
  }

  // 更新子弹位置
  bullets.value.forEach(bullet => {
    bullet.y -= BULLET_SPEED
  })

  // 更新敌人位置和射击
  enemies.value.forEach(enemy => {
    enemy.y += enemy.speed
    
    // 精英和Boss敌人的射击逻辑
    if ((enemy.type === 'elite' || enemy.type === 'boss') && 
        enemy.y > 0 && 
        Date.now() - enemy.lastShot > ENEMY_SHOOT_COOLDOWN) {
      enemyShoot(enemy)
      enemy.lastShot = Date.now()
    }
  })

  // 更新敌人子弹位置
  enemyBullets.value.forEach(bullet => {
    bullet.x += bullet.speedX
    bullet.y += bullet.speedY
  })

  // 移除超出屏幕的敌人子弹
  enemyBullets.value = enemyBullets.value.filter(bullet => 
    bullet.y < GAME_HEIGHT && 
    bullet.y > -BULLET_HEIGHT && 
    bullet.x > -BULLET_WIDTH && 
    bullet.x < GAME_WIDTH
  )

  // 更新道具位置
  powerUps.value.forEach(powerUp => {
    powerUp.y += powerUp.speed
  })

  // 检测碰撞
  checkCollisions()
}

// 碰撞检测
const checkCollisions = () => {
  // 子弹与敌人碰撞
  bullets.value = bullets.value.filter(bullet => {
    let bulletHit = false
    enemies.value = enemies.value.filter(enemy => {
      if (!bulletHit && isColliding(bullet, enemy)) {
        enemy.health--
        // 只有非激光子弹才会消失
        if (bullet.type !== 'laser') {
          bulletHit = true
        }
        if (enemy.health <= 0) {
          score.value += enemy.score
          if (score.value > highScore.value) {
            highScore.value = score.value
            localStorage.setItem('highScore', highScore.value)
          }
          createExplosion(enemy.x, enemy.y)
          
          // 检查关卡提升
          if (score.value >= level.value * 1000) {
            level.value++
          }
          return false
        }
      }
      return true
    })
    // 激光子弹会一直存在直到离开屏幕
    return bullet.type === 'laser' ? bullet.y > -BULLET_HEIGHT : !bulletHit && bullet.y > -BULLET_HEIGHT
  })

  // 玩家与敌人碰撞
  enemies.value = enemies.value.filter(enemy => {
    if (isColliding({ x: playerX.value, y: playerY.value, width: PLAYER_WIDTH, height: PLAYER_HEIGHT }, enemy)) {
      if (hasShield.value && powerUpLevels.value.shield > 0) {
        powerUpLevels.value.shield--
        if (powerUpLevels.value.shield === 0) {
          hasShield.value = false
        }
        sounds.hit.play()
      } else {
        lives.value--
        sounds.hit.play()
        if (lives.value <= 0) {
          gameOver.value = true
          clearInterval(gameLoop)
          clearInterval(enemySpawnInterval)
          clearInterval(powerUpSpawnInterval)
          sounds.background.pause()
        }
      }
      createExplosion(enemy.x, enemy.y)
      return false
    }
    return enemy.y < GAME_HEIGHT
  })

  // 玩家与敌人子弹碰撞
  enemyBullets.value = enemyBullets.value.filter(bullet => {
    if (isColliding({ x: playerX.value, y: playerY.value, width: PLAYER_WIDTH, height: PLAYER_HEIGHT }, bullet)) {
      if (hasShield.value && powerUpLevels.value.shield > 0) {
        powerUpLevels.value.shield--
        if (powerUpLevels.value.shield === 0) {
          hasShield.value = false
        }
        sounds.hit.play()
      } else {
        lives.value--
        sounds.hit.play()
        if (lives.value <= 0) {
          gameOver.value = true
          clearInterval(gameLoop)
          clearInterval(enemySpawnInterval)
          clearInterval(powerUpSpawnInterval)
          sounds.background.pause()
        }
      }
      createExplosion(bullet.x, bullet.y)
      return false
    }
    return true
  })

  // 玩家与道具碰撞
  powerUps.value = powerUps.value.filter(powerUp => {
    if (isColliding({ x: playerX.value, y: playerY.value, width: PLAYER_WIDTH, height: PLAYER_HEIGHT }, powerUp)) {
      activatePowerUp(powerUp.type)
      sounds.powerUp.play()
      return false
    }
    return powerUp.y < GAME_HEIGHT
  })
}

// 激活道具
const activatePowerUp = (type) => {
  switch(type) {
    case 'shield':
      hasShield.value = true
      powerUpLevels.value.shield++
      break
    case 'doubleShot':
      hasDoubleShot.value = true
      powerUpLevels.value.doubleShot++
      break
    case 'laser':
      hasLaser.value = true
      powerUpLevels.value.laser++
      break
  }
}

const isColliding = (rect1, rect2) => {
  return rect1.x < rect2.x + rect2.width &&
         rect1.x + rect1.width > rect2.x &&
         rect1.y < rect2.y + rect2.height &&
         rect1.y + rect1.height > rect2.y
}

// 暂停游戏
const togglePause = () => {
  isPaused.value = !isPaused.value
  if (isPaused.value) {
    sounds.background.pause()
  } else {
    sounds.background.play()
  }
}

// 游戏控制
const startGame = () => {
  gameStarted.value = true
  gameOver.value = false
  isPaused.value = false
  score.value = 0
  lives.value = 3
  level.value = 1
  playerX.value = GAME_WIDTH / 2 - PLAYER_WIDTH / 2
  bullets.value = []
  enemyBullets.value = []
  enemies.value = []
  powerUps.value = []
  explosions.value = []
  hasShield.value = false
  hasDoubleShot.value = false
  hasLaser.value = false
  powerUpLevels.value = {
    shield: 0,
    doubleShot: 0,
    laser: 0
  }

  gameLoop = setInterval(updateGame, 1000 / 60)
  enemySpawnInterval = setInterval(spawnEnemy, ENEMY_SPAWN_RATE)
  powerUpSpawnInterval = setInterval(spawnPowerUp, POWER_UP_SPAWN_RATE)
  
  sounds.background.loop = true
  sounds.background.play()
}

const restartGame = () => {
  startGame()
}

// 修改游戏信息显示，添加道具等级
const powerUpInfo = computed(() => {
  return {
    shield: powerUpLevels.value.shield > 0 ? `护盾 (${powerUpLevels.value.shield})` : null,
    doubleShot: powerUpLevels.value.doubleShot > 0 ? `双发 (${powerUpLevels.value.doubleShot})` : null,
    laser: powerUpLevels.value.laser > 0 ? `激光 (${powerUpLevels.value.laser})` : null
  }
})

// 生命周期钩子
onMounted(() => {
  gameArea.value.focus()
})

onUnmounted(() => {
  if (gameLoop) clearInterval(gameLoop)
  if (enemySpawnInterval) clearInterval(enemySpawnInterval)
  if (powerUpSpawnInterval) clearInterval(powerUpSpawnInterval)
  sounds.background.pause()
})
</script>

<style scoped>
.game-container {
  width: 800px;
  height: 600px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
  background: #f0f0f0;
}

.game-info {
  position: absolute;
  top: 10px;
  right: 10px;
  color: #333333;
  font-size: 20px;
  z-index: 1;
}

.power-ups {
  position: absolute;
  top: 120px;
  right: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.power-up {
  padding: 5px 10px;
  border-radius: 5px;
  font-size: 14px;
  color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 80px;
}

.power-up.shield {
  background-color: #00f;
}

.power-up.double-shot {
  background-color: #f0f;
}

.power-up.laser {
  background-color: #0ff;
}

.game-area {
  width: 100%;
  height: 100%;
  position: relative;
}

.player {
  width: 50px;
  height: 50px;
  position: absolute;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.shield-effect {
  position: absolute;
  top: -10px;
  left: -10px;
  right: -10px;
  bottom: -10px;
  border: 2px solid #00f;
  border-radius: 50%;
  animation: shield-pulse 1s infinite;
}

.bullet {
  width: 4px;
  height: 10px;
  position: absolute;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  background-color: #ffffff;
}

.laser-bullet {
  width: 8px;
  height: 20px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  background-color: #0ff;
  box-shadow: 0 0 10px #0ff;
  animation: laser-pulse 0.5s infinite;
}

.enemy {
  position: absolute;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.enemy-small {
  background-color: #ff0000;
}

.enemy-medium {
  background-color: #ff6600;
}

.enemy-large {
  background-color: #ff9900;
}

.enemy-elite {
  background-color: #ff00ff;
}

.enemy-boss {
  background-color: #00ffff;
}

.power-up-item {
  position: absolute;
  width: 30px;
  height: 30px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.shield-power {
  background-color: #00f;
}

.double-shot-power {
  background-color: #f0f;
}

.laser-power {
  background-color: #0ff;
}

.explosion {
  position: absolute;
  width: 40px;
  height: 40px;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
}

.start-screen,
.game-over,
.pause-screen {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #333333;
  background: rgba(240, 240, 240, 0.9);
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.controls {
  margin-top: 20px;
  font-size: 16px;
}

button {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: 18px;
  cursor: pointer;
  background-color: #00ff00;
  color: #000000;
  border: none;
  border-radius: 5px;
  transition: all 0.3s ease;
}

button:hover {
  transform: scale(1.05);
  opacity: 0.8;
}

@keyframes shield-pulse {
  0% { transform: scale(1); opacity: 0.5; }
  50% { transform: scale(1.1); opacity: 0.8; }
  100% { transform: scale(1); opacity: 0.5; }
}

@keyframes explode {
  0% { transform: scale(0); opacity: 1; }
  100% { transform: scale(2); opacity: 0; }
}

@keyframes laser-pulse {
  0% { opacity: 0.8; }
  50% { opacity: 1; }
  100% { opacity: 0.8; }
}

.enemy-bullet {
  width: 4px;
  height: 10px;
  position: absolute;
  background-color: #ff6600;
  border-radius: 2px;
}
</style> 